package com.chat.chatgptapi.api;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.chat.chatgptapi.bean.Msg;
import com.chat.chatgptapi.util.ChatConfig;
import com.chat.chatgptapi.bean.ChatMessage;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/chat")
@CrossOrigin
public class ChatApi {


    private static Map<String, List<Msg>> context = new HashMap<>();
    private String url="https://api.openai.com/v1/chat/completions";
    private String key="";

    @GetMapping("/getMessage")
    public SseEmitter send(String id){

        SseEmitter sseEmitter = new SseEmitter(-1L);
        System.out.println("get");
        System.out.println(id);
        List<Msg> messages = (List)context.get(id);
        System.out.println(messages.toString());
        if (messages != null) {

            JSONObject params = new JSONObject();
            // 添加参数
            params.put("model", "gpt-3.5-turbo");
            params.put("frequency_penalty", 0);

            params.put("messages", messages);
            params.put("max_tokens", 500);
            params.put("presence_penalty", 0.6);
            params.put("temperature", 0.5);
            params.put("top_p", 1);
            params.put("stream", true);

            ChatConfig chatConfig = new ChatConfig();

            InputStream inputStream = chatConfig.postMethod(params.toString(),url,key);

            if (inputStream != null) {
                chatConfig.readStream(inputStream, new ChatConfig.AnsMsgHandler() {
                    public void actMsg(InputStream is,  String line) {
                        try {
                            sseEmitter.send(line.replace("data: ",""));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }

        }
        return sseEmitter;
    }


    @PostMapping("/setMessage")
    public String data(@RequestBody ChatMessage chatMessage) {
        System.out.println(chatMessage);

        List<Msg> messages = (List)context.get(chatMessage.getId());

        if (messages != null) {
            context.remove(chatMessage.getId());
        }
        context.put(chatMessage.getId(),chatMessage.getMessages());
        return "ok";
    }

    @GetMapping("/deleteMessage")
    public void delete(String id) {
        System.out.println("delete");
        System.out.println(id);
        List<Msg> messages = (List)context.get(id);
        if (messages != null) {
            context.remove(id);
        }
        System.out.println(context.get(id));
    }


}
